1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| #include<iostream> #include<cstdio> #include<cstring> #include<cctype> #include<algorithm> #include<cmath> #define int long long using namespace std; inline int read(){ int w=0,x=0;char c=getchar(); while(!isdigit(c))w|=c=='-',c=getchar(); while(isdigit(c))x=(x<<3)+(x<<1)+(c^48),c=getchar(); return w?-x:x; } namespace star { const int maxn=1e5+10,mod=1e9+7; int n; int ecnt,head[maxn],to[maxn<<1],nxt[maxn<<1],v[maxn<<1]; inline void addedge(int a,int b,int c){ to[++ecnt]=b,nxt[ecnt]=head[a],head[a]=ecnt,v[ecnt]=c; to[++ecnt]=a,nxt[ecnt]=head[b],head[b]=ecnt,v[ecnt]=c; } inline int up(int a){return a>=mod?a-mod:a;} inline int dn(int a){return a<0?a+mod:a;} int f[maxn],f2[maxn],g[maxn],g2[maxn],dep[maxn],fa[maxn][21],dis[maxn],siz[maxn]; void dfs(int x,int father){ fa[x][0]=father;siz[x]=1; dep[x]=dep[father]+1; for(int i=0;i<20;i++) fa[x][i+1]=fa[fa[x][i]][i]; for(int i=head[x];i;i=nxt[i]){ int u=to[i]; if(u==father)continue; dis[u]=dis[x]+v[i]; dfs(u,x); siz[x]+=siz[u]; f[x]=up(f[x]+up(f[u]+siz[u]*v[i]%mod))%mod; f2[x]=((f2[x]+f2[u])%mod+(siz[u]*v[i]%mod*v[i]%mod+2*v[i]*f[u]%mod)%mod)%mod; } } void dfs2(int x){ for(int i=head[x];i;i=nxt[i]){ int u=to[i]; if(u==fa[x][0])continue; g[u]=(g[x]+(n-2*siz[u]+mod)%mod*v[i]%mod)%mod; g2[u]=((f2[u]+(g2[x]-((f2[u]+2*v[i]%mod*f[u]%mod)%mod+siz[u]*v[i]%mod*v[i]%mod)%mod+mod)%mod)%mod+((g[x]-f[u]+mod-siz[u]*v[i]%mod+mod)%mod*2%mod*v[i]%mod+(n-siz[u])*v[i]%mod*v[i]%mod)%mod)%mod; dfs2(u); } } inline int LCA(int x,int y){ if(dep[x]<dep[y])swap(x,y); for(int i=20;~i;i--) if(dep[fa[x][i]]>=dep[y]) x=fa[x][i]; if(x==y) return x; for(int i=20;~i;i--) if(fa[x][i]!=fa[y][i]) x=fa[x][i],y=fa[y][i]; return fa[x][0]; } inline void work(){ n=read(); for(int u,v,i=1;i<n;i++) u=read(),v=read(),addedge(u,v,read()); dfs(1,0); g[1]=f[1],g2[1]=f2[1]; dfs2(1); int Q=read(); while(Q--){ int y=read(),x=read(),lca=LCA(x,y),d=dis[x]+dis[y]-dis[lca]*2; d%=mod; if(lca==x){ printf("%lld\n",(g2[y]-2*((((g2[x]-f2[x]+mod)%mod+2*d%mod*(g[x]-f[x]+mod)%mod)%mod+d*d%mod*(n-siz[x])%mod)%mod+mod)%mod+mod)%mod); }else{ printf("%lld\n",((((f2[x]%mod+2%mod*d%mod*f[x]%mod)%mod+d%mod*d%mod*siz[x]%mod)%mod*2%mod-g2[y]%mod)%mod+mod)%mod); } } } } signed main(){ star::work(); return 0; }
|